package cn.itsource.basic.service;

import cn.itsource.basic.basicMapper.BasicMapper;
import cn.itsource.basic.domain.baseDomain;
import cn.itsource.basic.util.PageList;
import cn.itsource.org.query.BaseQuery;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 抽业务实现层
 */
public class BaseServiceImpl<T extends baseDomain, Q extends BaseQuery> implements BaseService<T, Q> {
    @Autowired
    private BasicMapper<T> basicMapper;

    @Override
    public PageList<T> findPage(Q q) {
//        分页
        PageHelper.startPage(q.getPage(), q.getSize());
//        执行分页语句(如果要使用高级查询就覆写)
        List<T> ts = basicMapper.selectAll();
//        封装到pageInfo中
        PageInfo<T> tPageInfo = new PageInfo<>(ts);
//        将pageInfo封装到自定义pagelist中
        PageList pageList = new PageList<>(tPageInfo.getTotal(), tPageInfo.getList());
//        返回至前端
        return pageList;
    }

    //查询一个
    @Override
    public T findOne(Long id) {
        return basicMapper.selectByPrimaryKey(id);
    }

    //查询全部数据
    @Override
    public List<T> findAll() {
        return basicMapper.selectAll();
    }

    //修改
    @Override
    public void update(T t) {
        //只有设置了值的字段才会被修改
        basicMapper.updateByPrimaryKeySelective(t);
    }

    //添加
    @Override
    public void save(T t) {
//        只有设置了值的字段才会被添加
        basicMapper.insertSelective(t);

    }

    //删除
    @Override
    public void delete(Long id) {
//        根据id删除
        basicMapper.deleteByPrimaryKey(id);
    }

    //批量删除
    @Override
    public void batchRemove(Q q) {
        if (q.getIds() == null || q.getIds().length == 0) {
            return;
        }
        basicMapper.batchRemove(q.getIds());
    }
}
